<template>
  <el-menu
    :collapse="collapse"
    :default-active="activeMenu.defaultActive"
    :default-openeds="activeMenu.defaultOpeneds">
    <el-sub-menu
      v-for="menu in menus"
      :key="menu.id"
      :index="String(menu.id)">
      <template #title>
        <el-icon>
          <UserFilled />
        </el-icon>
        <span>{{ menu.title }}</span>
      </template>
      <el-menu-item
        v-for="m2 in menu.children"
        :key="m2.id"
        :index="String(m2.id)"
        @click="clickMenu(m2, menu)">
        {{ m2.title }}
      </el-menu-item>
    </el-sub-menu>
  </el-menu>
</template>

<script lang="ts">
import { activeMenuSession } from '@/storage/session'
import { defineComponent, reactive, ref, onMounted } from 'vue'
import { Menu, menus } from '../frame.service'

export default defineComponent({
  name: 'pl-frame-sidebar',
  emits: {
    clickMenu: (menu: Menu, parent: Menu) => true,
  },
  setup(props, ctx) {
    const collapse = ref(false)
    const activeMenu = reactive(activeMenuSession.getData())
    const clickMenu = (menu: Menu, parent: Menu) => {
      activeMenu.defaultActive = String(menu.id)
      activeMenu.defaultOpeneds = [String(parent.id)]
      activeMenuSession.set({
        defaultActive: String(menu.id),
        defaultOpeneds: [String(parent.id)],
      })

      ctx.emit('clickMenu', menu, parent)
    }

    onMounted(() => {
      if (activeMenu.defaultActive && activeMenu.defaultOpeneds.length) {
        const menu = Menu.getMenu(Number(activeMenu.defaultActive))
        const parent = Menu.getMenu(Number(activeMenu.defaultOpeneds[0]))
        if (menu && parent) {
          ctx.emit('clickMenu', menu, parent)
        }
      }
    })

    return {
      collapse,
      menus,
      activeMenu,
      clickMenu,
    }
  },
})
</script>
